package com.main.gateway.infrastructure.utils.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.time.LocalDateTime;

@Component
public class EntryFilter implements GlobalFilter, Ordered {

    @Value("${server.servlet.context-path}")
    private String ContextPath;
    private static final String GATEWAY_TOKEN_HEADER = "X-Gateway-Token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println();
        System.out.println(LocalDateTime.now());
        System.out.println("经过第-1个过滤器EntryFilter");
        System.out.println();

        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
//        if (url.contains("/websocket/")) {
//            return chain.filter(exchange);  // 直接放行WebSocket请求
//        }
//      检查请求头中是否有特定的网关令牌
        String gatewayToken = request.getHeaders().getFirst(GATEWAY_TOKEN_HEADER);
        if (gatewayToken != null && gatewayToken.equals("Mes-Robot-Gateway-Token")) {
            request = request.mutate().header("fromGateway", "true").build();
        }
        String apiDocPath = "/v3/api-docs";
        String apiContextDocPath = ContextPath+"/v3/api-docs";
        if(request.getPath().toString().endsWith(apiDocPath)&& !request.getPath().toString().endsWith(apiContextDocPath)){
            String uri = request.getURI().toString().replace(apiDocPath,apiContextDocPath);
            request= exchange.getRequest().mutate().uri(URI.create(uri)).build();
        }
        System.out.println(request.getPath());
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        // 确保过滤器在其他过滤器之前运行
        return -1;
    }
}